var mysql = require('mysql');


export class MySql {
    private connection: any;
    constructor() {
        this.connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: '123',
            database: 'gather'
        });

    }

    /**
     * 创建连接
     */
    public connect() {
        this.connection.connect();
        //测试是否链接成功
        this.connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (error) throw error;
            console.log('The solution is: ', results[0].solution);
        });
    }


    /**
     * 查询sql
     * @param sql 
     */
    public query(QuerySql: string) {
      //  this.connect(); 
       let $this = this; 
        return new Promise(function (resolve, reject) { 
            $this.connection.query(QuerySql, function (err, result) { 
             //   this.connection.end();
                if (err) {
                    console.log('[SELECT ERROR] - ', err.message);
                    reject(err);
                }
                else {
                    resolve(result);
                }

            });

        });
    }


    /**
     * 新增
     * @param InsertSql 
     */
    public insert(InsertSql: string, Params?:Array<any>) {
       // this.connect();
       let $this = this;
        return new Promise(function (resolve, reject) {

            $this.connection.query(InsertSql, Params, function (err, result) {
               // this.connection.end();
                if (err) {
                    console.log('[INSERT ERROR] - ', err.message);
                    reject(err);
                }
                else {
                    resolve(result);
                }
            });
        });
    }



    /**
  * 更新
  * @param UpdateSql 
  */
    public update(UpdateSql: string, Params?:Array<any>) {
      //  this.connect();
      let $this = this;
        return new Promise(function (resolve, reject) {

            $this.connection.query(UpdateSql, Params, function (err, result) {
              //  this.connection.end();
                if (err) {
                    console.log('[UPDATE  ERROR] - ', err.message);
                    reject(err);
                }
                else {
                    resolve(result);
                }
            });
        });
    }



    /**
    * 删除
    * @param DeleteSql 
    */
    public delete(DeleteSql: string) {
        //this.connect();
        let $this = this;
        return new Promise(function (resolve, reject) {

            $this.connection.query(DeleteSql, function (err, result) {
               // this.connection.end();
                if (err) {
                    console.log('[DELETE   ERROR] - ', err.message);
                    reject(err);
                }
                else {
                    resolve(result);
                }
            });
        });
    }

}





